package com.david.viewtest.view

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ImageSpan
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import java.io.File

/**
 * 文本长时换行的带标签labelView，如果最多一行时可使用TextLabelView放在此View后面
 *
 * 没有文本只有文本标签（爆 热 减等）或icon标签时参考[com.david.viewtest.view.MultiLabelView]
 *
 */
class TextViewWithLabels(context: Context, attrs: AttributeSet): AppCompatTextView(context, attrs) {
    private var baseContent: String? = null
    private var preLabelBitmaps = ArrayList<TextViewLabelBean>()
    private var endLabelBitmaps = ArrayList<TextViewLabelBean>()

    //列表传入int类型的resId/string类型的imgUrl
    fun setContentAndTag(content: String?, startTagReses: List<Any>? = null, endTagReses: List<Any>?) {
        preLabelBitmaps.clear()
        endLabelBitmaps.clear()

        baseContent = null
        if (startTagReses.isNullOrEmpty() && endTagReses.isNullOrEmpty()) {
            text = content
            return
        }
        baseContent = content

        if (!startTagReses.isNullOrEmpty()) {
            for (item in startTagReses) {
                if (item is Int && item > 0) {
                    preLabelBitmaps.add(TextViewLabelBean(BitmapFactory.decodeResource(context.resources, item)))
                    setContentAndLabels()
                } else if (item is String) {
                    val bean = TextViewLabelBean()
                    preLabelBitmaps.add(bean)
                    Glide.with(this).downloadOnly()
                        .load(item)
                        .listener(object: RequestListener<File> {

                            override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<File>, isFirstResource: Boolean): Boolean {
                                return true
                            }

                            override fun onResourceReady(resource: File, model: Any, target: Target<File>?, dataSource: DataSource, isFirstResource: Boolean): Boolean {
                                bean.bitmap = BitmapFactory.decodeFile(resource.path)
                                setContentAndLabels()
                                return true
                            }

                        }).preload()
                }
            }
        }

        if (!endTagReses.isNullOrEmpty()) {
            for (item in endTagReses) {
                if (item is Int && item > 0) {
                    endLabelBitmaps.add(TextViewLabelBean(BitmapFactory.decodeResource(context.resources, item)))
                    setContentAndLabels()
                } else if (item is String) {
                    val bean = TextViewLabelBean()
                    endLabelBitmaps.add(bean)
                    Glide.with(this).downloadOnly()
                        .load(item)
                        .listener(object: RequestListener<File> {

                            override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<File>, isFirstResource: Boolean): Boolean {
                                return true
                            }

                            override fun onResourceReady(resource: File, model: Any, target: Target<File>?, dataSource: DataSource, isFirstResource: Boolean): Boolean {
                                bean.bitmap = BitmapFactory.decodeFile(resource.path)
                                setContentAndLabels()
                                return true
                            }

                        }).preload()
                }
            }
        }
    }


    private fun setContentAndLabels() {
        val builder = SpannableStringBuilder()
        if (preLabelBitmaps.isNotEmpty()) {
            for (item in preLabelBitmaps) {
                val bitmap = item.bitmap ?: continue
                builder.append(".")

                val d: Drawable = BitmapDrawable(context.resources, bitmap)
                d.setBounds(0, 0, bitmap.width, bitmap.height);//缺少这句的话，不会报错，但是图片不回显示
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    builder.setSpan(ImageSpan(d, ImageSpan.ALIGN_CENTER), builder.length - 1, builder.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                } else {
                    builder.setSpan(ImageSpan(d, ImageSpan.ALIGN_BASELINE), builder.length - 1, builder.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                }

                builder.append(" ")
            }
        }
        builder.append(baseContent)


        if (!endLabelBitmaps.isNullOrEmpty()) {
            for (item in endLabelBitmaps) {
                val bitmap = item.bitmap ?: continue
                builder.append(" .")

                val d: Drawable = BitmapDrawable(context.resources, bitmap)
                d.setBounds(0, 0, bitmap.width, bitmap.height);//缺少这句的话，不会报错，但是图片不回显示

                builder.setSpan(ImageSpan(d, ImageSpan.ALIGN_CENTER), builder.length - 1, builder.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            }
        }
        text = builder
    }

    data class TextViewLabelBean(
        var bitmap: Bitmap? = null
    )
}